package com.lam.mall.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lam.common.base.controller.BaseController;
import com.lam.common.base.domain.Result;
import com.lam.common.context.TokenUtils;
import com.lam.common.exception.ParameterErrorException;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.StringUtils;
import com.lam.common.validate.ValidateUtil;
import com.lam.common.validate.group.Add;
import com.lam.common.validate.group.Update;
import com.lam.common.validate.model.ValidOperType;
import com.lam.framework.annotation.ParamInject;
import com.lam.framework.operLog.annotation.Log;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.mall.common.constant.MallConstant;
import com.lam.mall.entity.ProdSpecs;
import com.lam.mall.entity.ProdSpecsValue;
import com.lam.mall.param.ProdSpecsParam;
import com.lam.mall.param.ProdSpecsValueParam;
import com.lam.mall.service.ProdSpecsService;
import com.lam.mall.service.ProdSpecsValueService;

/**
 * 规格管理Controller
 * 
 * @author admin
 * @date 2023-04-21
 */
@Log(title = "规格管理")
@ParamInject
@RestController
@RequestMapping("/${adminPath}/mall/prodSpecs")
public class ProdSpecsController extends BaseController {

    @Autowired
    private ProdSpecsService prodSpecsService;
    @Autowired
    private ProdSpecsValueService prodSpecsValueService;

    /**
     * 获取所有的规格
     */
    @GetMapping("/listAll")
    public Result list() {
        ProdSpecsParam param = new ProdSpecsParam();
        param.setShopId(TokenUtils.getLoginUserShopId());
		List<ProdSpecs> list = prodSpecsService.selectList(param );
        return Result.ok(list);
    }

    /**
     * 根据规格id获取规格值
     */
    @Log(oper="根据规格id获取规格值")
    @PreAuthorize("@ss.hasPm('mall:prodSpecs:list')")
    @GetMapping("/listSpecValue/{specId}")
    public Result listSpecValue(@PathVariable("specId") String specId) {
		ProdSpecsValueParam param = new ProdSpecsValueParam();
		param.setSpecsId(specId);
		List<ProdSpecsValue> list = prodSpecsValueService.selectList(param );
        return Result.ok(list);
    }
    
    /**
     * 根据获取规格值最大的自增id
     */
    @Log(oper="查询规格值最大的id")
    @PreAuthorize("@ss.hasPm('mall:prodSpecs:list')")
    @GetMapping("/listSpecMaxValueId")
    public Result listSpecMaxValueId() {
    	Long id = prodSpecsValueService.listSpecMaxValueId();
        return Result.ok(id);
    }
    
    /**
     * 查询规格管理列表
     */
    @Log(oper="分页查询")
    @PreAuthorize("@ss.hasPm('mall:prodSpecs:list')")
    @GetMapping("/list")
    public Result list(ProdSpecsParam param) {
    
    	param.setShopId(TokenUtils.getLoginUserShopId());
    	startPage();
        List<ProdSpecs> list = prodSpecsService.selectList(param);
        if(CollectionUtil.isNotEmpty(list)) {
        	ProdSpecsValueParam valueParam = new ProdSpecsValueParam();
            for (ProdSpecs specs : list) {
            	valueParam.setSpecsId(specs.getId());
            	specs.setProdSpecsValues(prodSpecsValueService.selectList(valueParam));
    		}
        }
        return Result.ok(getTableData(list));
    }

    /**
     * 获取规格管理详细信息
     */
    @Log(oper="根据ID查询")
    @PreAuthorize("@ss.hasPm('mall:prodSpecs:query')")
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable("id") String id) {
    
    	ProdSpecs specs = prodSpecsService.selectById(id);
    	if(specs != null) {
    		ProdSpecsValueParam valueParam = new ProdSpecsValueParam();
    		valueParam.setSpecsId(specs.getId());
    		specs.setProdSpecsValues(prodSpecsValueService.selectList(valueParam));
    	}
        return Result.ok(specs);
    }

    /**
     * 新增规格管理
     */
    @PreAuthorize("@ss.hasPm('mall:prodSpecs:add')")
    @Log(businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated(Add.class) @RequestBody ProdSpecs prodSpecs) {
    
    	prodSpecs.setShopId(TokenUtils.getLoginUserShopId());
        ValidateUtil.validUnique(prodSpecs, ValidOperType.ADD, MallConstant.UNIQUE_PROD_SPECS_SPECS_NAME, "规格名称已存在！");
        checkProdSpecsValue(prodSpecs);
        return toAjax(prodSpecsService.insert(prodSpecs));
    }
    
    private void checkProdSpecsValue(ProdSpecs prodSpecs) {
    	Set<String> set = new HashSet<>();
    	for (ProdSpecsValue v : prodSpecs.getProdSpecsValues()) {
    		if(StringUtils.isBlank(v.getSpecsValue())) {
    			throw new ParameterErrorException("有规格值为空，请检查");
    		}
    		if(set.contains(v.getSpecsValue())) {
    			throw new ParameterErrorException("存在规格值重复，请检查");
    		}
    		set.add(v.getSpecsValue());
		}
    }

    /**
     * 修改规格管理
     */
    @PreAuthorize("@ss.hasPm('mall:prodSpecs:edit')")
    @Log(businessType = BusinessType.UPDATE)
    @PutMapping
    public Result edit(@Validated(Update.class) @RequestBody ProdSpecs prodSpecs) {
    
    	prodSpecs.setShopId(TokenUtils.getLoginUserShopId());
        ValidateUtil.validUnique(prodSpecs, ValidOperType.UPDATE, MallConstant.UNIQUE_PROD_SPECS_SPECS_NAME, "规格名称已存在！");
    	checkProdSpecsValue(prodSpecs);
        return toAjax(prodSpecsService.update(prodSpecs));
    }

    /**
     * 删除规格管理
     */
    @PreAuthorize("@ss.hasPm('mall:prodSpecs:remove')")
    @Log(businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public Result remove(@PathVariable String id) {
    
        return toAjax(prodSpecsService.deleteById(id));
    }

}
